package com.servlet;

import com.Imp.CartMapperImpl;
import com.Imp.CuisineMapperImpl;
import com.entity.Cart;
import com.entity.Cuisine;
import com.mapper.CartMapper;
import com.mapper.CuisineMapper;
import com.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class CartController extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request,response);
    }

    public void  doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
        String op=request.getParameter("op");
        String cuisineId = request.getParameter("cuisineId"); //获取菜品号
        //获取用户账户
        HttpSession session=request.getSession();
        String userName = (String) session.getAttribute("username");
        //由菜品号从菜品列表中获取菜品信息
        CuisineMapper cuisineMapper = new CuisineMapperImpl();
        Cuisine cuisine = cuisineMapper.getCuisineByCuisineId(cuisineId);
        //将菜品信息加入购物车实体中
        Cart cart = new Cart(cuisine.getStoreId(),userName,cuisine.getCuisineId(),cuisine.getCuisineName(),cuisine.getPrice());
        CartService cartService=new CartService();
        if(op.equals("add")){
            // 添加菜品到购物车
            cartService.addToCart(cart);
            // 设置请求参数
            String redirectUrl = "/menu.jsp?id=" + cuisine.getStoreId();
            // 重定向到指定页面
            response.sendRedirect(redirectUrl);
        }
        else if(op.equals("add_1")){
            // 添加菜品到购物车
            cartService.addToCart(cart);
            // 设置请求参数
            String redirectUrl = "/cart.jsp";
            // 重定向到指定页面
            response.sendRedirect(redirectUrl);
        }
        else if(op.equals("delete_all")){
            //删除菜品
            CartMapper cartMapper = new CartMapperImpl();
            cartMapper.deleteFromCart(cart.getStoreId(),cart.getCustomerId(),cart.getCuisineId());
            // 设置请求参数
            String redirectUrl = "/cart.jsp";
            // 重定向到指定页面
            response.sendRedirect(redirectUrl);
        }
        else if(op.equals("delete")){
            // 从购物车中减少菜品数量
            cartService.deleteFromCart(cart);
            // 设置请求参数
            String redirectUrl = "/cart.jsp";
            // 重定向到指定页面
            response.sendRedirect(redirectUrl);
        }
        else{
            System.out.println("123");
        }
    }

}

